package com.snails.app.glide;

import android.content.Context;
import android.os.Looper;

import com.bumptech.glide.Glide;
import com.snails.app.SnailsApp;
import com.snails.net.utils.FileUtil;

/**
 * @author lawrence
 * @date 2019-05-15 09:55
 */
public final class GlideHelper {
    private final Context appCtx;

    private GlideHelper() {
        appCtx = SnailsApp.instance().getCtx();
    }

    public static GlideHelper instance() {
        return GlideHelperHolder.INSTANCE;
    }

    private static final class GlideHelperHolder {
        private static final GlideHelper INSTANCE = new GlideHelper();
    }

    // ----------------------------------------------------------------------------
    // -----------  ------------
    // ----------------------------------------------------------------------------
    /**
     * 清除图片磁盘缓存
     */
    public void clearImageDiskCache() {
        try {
            if (Looper.myLooper() == Looper.getMainLooper()) {
                new Thread(() -> Glide.get(appCtx).clearDiskCache()).start();
            } else {
                Glide.get(this.appCtx).clearDiskCache();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 清除图片内存缓存
     */
    public void clearImageMemoryCache() {
        try {
            // 只能在主线程执行
            if (Looper.myLooper() == Looper.getMainLooper()) {
                Glide.get(this.appCtx).clearMemory();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 清除图片所有缓存
     */
    public void clearImageAllCache() {
        clearImageDiskCache();
        clearImageMemoryCache();
    }

    /**
     * 获得Glide缓存的图片文件, 格式化后大小
     * @return {B、KB、MB、GB、TB}
     */
    public String getCacheSize() {
        return FileUtil.formatFileSize(SnailsGlideModule.getFolder());
    }

}
